package org.bdware.doip.endpoint.doipClient;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import org.bdware.doip.core.codec.DelimiterMessageClientCodec;
import org.bdware.doip.core.crypto.GlobalCertifications;
import org.bdware.doip.core.utils.GlobalConfigurations;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLEngine;
import java.net.URI;
import java.net.URISyntaxException;

public class NettyDoipTlsClientChannel extends NettyDoipClientChannel {

    private static final byte[] EOF = {'\n', '#', '\n' ,'#', '\n'};
    EventLoopGroup group;


    public NettyDoipTlsClientChannel() {

    }

    protected SslContext getSSLContext() throws Exception {
        KeyManagerFactory keyManagerFactory;
        keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(GlobalCertifications.getGlobalKeyStore(), GlobalConfigurations.JKSPassword.toCharArray());

        SslContext sslCtx = SslContextBuilder.forClient()
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .build();
        return sslCtx;
    }

    @Override
    public void close() {
        if(handler != null) handler.close();
        if(group != null) {
            //Future<?> future = group.shutdownGracefully();
            //future.syncUninterruptibly();
            group.shutdownGracefully();
        }
        remoteAddress = null;
        isConnected = false;
    }

    @Override
    public void connect(String targetUrl) throws URISyntaxException {
        URI uri = new URI(targetUrl);
        logger.debug("[URI Parse]scheme:" + uri.getScheme() + "  host: " + uri.getHost() + "  port: " + uri.getPort());
        final Bootstrap b = new Bootstrap();
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
        group = new NioEventLoopGroup();
        b.group(group);
        handler = new NettyDoipClientHandler();
        b.channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        SSLEngine engine = getSSLContext().newEngine(ch.alloc());
//                                engine.setUseClientMode(false);
                        ch.pipeline()
                                .addFirst(new SslHandler(engine))
                                .addLast(new DelimiterBasedFrameDecoder(GlobalConfigurations.defaultMsgMTU, Unpooled.copiedBuffer(EOF)))
                                .addLast(new DelimiterMessageClientCodec())
                                .addLast(handler);
                    }
                });
        logger.debug("[DoipClient] Create TLS Client!");
        try {
            logger.debug("[URI Parse]host: "+ uri.getHost() + "  port: " + uri.getPort());
            channel = b.connect(uri.getHost(), uri.getPort()).sync().channel();
            handler.setChannel(channel);
        }catch (Exception e){
            e.printStackTrace();
        }
        isConnected = true;
    }
}
